<template>
  <div class="copy-delete-box">
    <a class="copy" title="复制" :class="activeClass" @click.stop="handleCopy">
      <Icon icon="copy|svg" size="14" />
    </a>
    <a class="delete" title="删除" :class="activeClass" @click.stop="handleDelete">
      <Icon icon="ant-design:delete-outlined" size="16" />
    </a>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent } from 'vue';
  import { IVFormComponent } from '../../../typings/v-form-component';
  import { remove } from '../../../utils';
  import { useFormDesignState } from '../../../hooks/useFormDesignState';
  import Icon from '/@/components/Icon/index';

  export default defineComponent({
    name: 'FormNodeOperate',
    components: {
      Icon,
    },
    props: {
      schema: {
        type: Object,
        default: () => ({}),
      },
      currentItem: {
        type: Object,
        default: () => ({}),
      },
    },
    setup(props) {
      const { formConfig, client, formDesignMethods } = useFormDesignState();
      const activeClass = computed(() => {
        return props.schema.field === props.currentItem.field ? 'active' : 'unactivated';
      });
      /**
       * 删除当前项
       */
      const handleDelete = () => {
        const traverse = (schemas: IVFormComponent[]) => {
          schemas.some((formItem, index) => {
            const { component, field } = formItem;

            // 处理栅格和标签页布局
            ['Grid', 'Tabs'].includes(component) &&
              formItem.columns?.forEach((item) => traverse(item.children));

            if (field === props.currentItem.field) {
              let params: IVFormComponent = { component: '', componentProps: {} };

              if (schemas.length > 1) {
                const comp = schemas[index + 1];
                params = schemas[index - 1] || comp;
              }

              formDesignMethods.handleSetSelectItem(params, true);
              remove(schemas, index);
              return true;
            }
          });
        };
        traverse(formConfig.value!.schemas[client.value]);
      };

      const handleCopy = () => {
        formDesignMethods.handleCopy();
      };
      return { activeClass, handleDelete, handleCopy };
    },
  });
</script>
